/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.query.filter;

import java.sql.PreparedStatement;
import java.util.Collection;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.beanutils.PropertyUtils;

import com.koylu.caffein.converter.Converter;
import com.koylu.caffein.model.caffein.CaffeinConfig;
import com.koylu.caffein.model.clazz.Clazz;
import com.koylu.caffein.model.clazz.Column;
import com.koylu.caffein.query.Query;

public class In extends Filter {

	private Column column;
	private String alias;
	private String path;
	private Object[] realValue;
	private String value;
	private StringBuffer query = null;
	private Query columnTargetedQuery;
	
	public In() {}

	public In(String alias, String path, Object... value) {
		this.alias = alias;
		this.path = path;
		if(value == null || value.length == 0){
			throw new RuntimeException("value is null or empty");
		}
		this.realValue = value;
	}
	
	public In(String alias, String path, Query query) {
		this.alias = alias;
		this.path = path;
		this.columnTargetedQuery = query;
	}
	
	public String getAlias() {
		return alias;
	}
	
	public void setAlias(String alias) {
		this.alias = alias;
	}
	
	public String getPath() {
		return path;
	}
	
	public void setPath(String path) {
		this.path = path;
	}
	
	public Object[] getRealValue() {
		return realValue;
	}
	
	public void setRealValue(Object[] realValue) {
		this.realValue = realValue;
	}
	
	public String getValue() {
		return value;
	}
	
	public void setValue(String value) {
		this.value = value;
	}
	
	public StringBuffer toQuery(CaffeinConfig caffeinConfig, Map<String, Clazz> aliasMap) throws Exception {
		if(query == null){
			query = new StringBuffer();
			if(columnTargetedQuery != null){
				if( columnTargetedQuery.getTarget() instanceof com.koylu.caffein.query.target.Column ){
					realValue = columnTargetedQuery.list().toArray();
					if(realValue == null || realValue.length == 0){
						throw new RuntimeException("value is null or empty for query-->"+columnTargetedQuery.getQuery());
					}
				}
			}
			if (column == null) {
				if(aliasMap.containsKey(alias)){
					column = aliasMap.get(alias).pathToColumn(caffeinConfig, path);
					if(column == null){
						throw new RuntimeException("invalid clazz path:"+path);
					}
				}else{
					throw new RuntimeException("invalid clazz alias:"+alias);
				}
			}
			query.append(alias).append(".").append(column.getColumn()).append(" IN (");	
			for (int i = 0; i < realValue.length; i++) {
				query.append("?");
				if(i+1 < realValue.length){
					query.append(",");	
				}
			}
			query.append(")");
		}
		return query;
	}
	
	public int fieldToColumn(CaffeinConfig caffeinConfig, PreparedStatement preparedStatement, int index) throws Exception{
		if(realValue != null && realValue.length > 0){
			Converter converter = column.getConverter(caffeinConfig); 
			for (Object value : realValue) {
                converter.fieldToColumn(preparedStatement, value, false, index);
                index = index + 1;
            }
		}
		return index;
	}
	
	@SuppressWarnings("rawtypes")
	public void resolveValue(Object object) throws Exception {
		if(value != null){
			if(value.contains(",")){
				StringTokenizer tokenizer = new StringTokenizer(value, ",");
				int tokenCount = tokenizer.countTokens();
				if(tokenCount > 0){
					realValue = new Object[tokenCount];
					for (int i = 0; i < tokenCount; i++) {
						realValue[i] = tokenizer.nextToken();
					}					
				}
			}else{
				String token = getToken(value);
				if(token != null){
					Object realValue = null;
					try {
						realValue = PropertyUtils.getNestedProperty(object, token);
					} catch (Exception e) {}
					if(realValue instanceof Collection){
						setRealValue(((Collection)realValue).toArray());
					}else{
						setRealValue((Object[])realValue);						
					}
				}
			}
		}
	}
}